//
//  XLQauchViewController.swift
//  XLVeibo
//
//  Created by macbook on 16/6/25.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit
import SVProgressHUD

class XLQauchViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view = webView
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    //设置导航栏
    private func setupNav(){
     
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(XLQauchViewController.cancelClcik))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(XLQauchViewController.autoFillClick))
        
    }
    
    //取消按钮的实现
    @objc private func cancelClcik(){
    
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    //自动填充按钮的实现jsString 自动填充
    @objc private func autoFillClick(){
    
    print("点击了")
        let jsSting = "document.getElementById('userId').value='13022285567',document.getElementById('passwd').value='buzhiduicuo'"
        
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsSting)
    
    }
    
     /*
     App Secret
     19a2416ff0ed76fee81c4a482593c260
     http://www.baidu.com
     
     App Key：3634844374
     App Secret：19a2416ff0ed76fee81c4a482593c260
     */
    
    private lazy var webView: UIWebView = {
    
        let webViews = UIWebView()
        
        webViews.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
  
        let request = NSURLRequest(URL: url!)
        
        webViews.loadRequest(request)
    
        return webViews
    }()
    
}


extension XLQauchViewController:UIWebViewDelegate{

    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
      SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    }
    
    //web将要加载request
    //如果返回 true 代码继续加载   如果返回false代码停止加载  默认不实现，代表true
    
    //截取code吗
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //把url 转换成字符串
        let urlString = request.URL?.absoluteString
//        print(urlString)
        //判断URLstring 睡否有值
//        urlString?.hasPrefix(<#T##prefix: String##String#>)  括号中添加的是回调页、
        
        
        if let u = urlString where  u.hasPrefix(REDIRECT_URI){
            
            //参数键值对 code码
            let qusest = request.URL?.query
            print("键值对\(qusest)")
            //可选值判断
            if let q = qusest {
              //字符串截取code  拿到code码之后获取accessToken
                let code = q.substringFromIndex("code=".endIndex)
             
                //给下面的参数传递数据
                loadUserAccess(code)
//                print(code)
            }
        }
        return true
    }
}


//获取accesssToken
extension XLQauchViewController{
    
    func loadUserAccess(code: String){

    
        XLNetworkTools.sharedTools.oauthLoadUserAccout(code, success: { (response) in
            //判断请求回来的response 是否有值，而且是否可以转成一个字典
            //如果在判断是否有值，而且是否可以转换成你想要的类型，一般情况下用 as?
            guard let res = response as? [String: AnyObject]else {
            
                print("返回数据不是一个字典")
                return
            }
            
            let userAccount = XLUserAccount(dict: res)
           
            print("返回=\(userAccount)")
            self.loadUserInfo(userAccount)
            }) { (error) in
                
                print(error)
        }
    }
    
    
    //把token和uid 传递进去就可以获得个人信息
    func loadUserInfo(userAccount: XLUserAccount){
        
        XLNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, sucess: { (responst) in
            
            //获取到的数据
   print(responst)
            //判断是否有值 而且是否可以转成字典
            guard let res = responst as? [String:AnyObject] else {
                
                return
                
            }
            
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            //通过归档保存数据

            XLUserAccountTools.sharedTools.saveUserAccount(userAccount)
        self.dismissViewControllerAnimated(false, completion: { 
            
            //关闭指示器
            SVProgressHUD.dismiss()
            
            //发布通知
            NSNotificationCenter.defaultCenter().postNotificationName(SwiftRootViewController, object: nil)
        })
            
            
            
              //拿到头像和名称数据
//            print(userAccount)
        }) { (error) in
            
            print("失败\(error)")
        }
        
    }


}











